import util from '@/libs/util';
import utilDate from '@/util/getDate';
import Cookies from 'js-cookie';
import customTree from '../studentsignup/customTree.vue';
import books from '../book/bookList.vue';
import classroomComp from '../classroom/classroomlist.vue';
import classTimeModel from './classTimeModel.js';

export default {
    components: {
        customTree, books, classroomComp
    },
    data () {
        return {
            columnsSchedule: [{
                title: '上课周期',
                key: 'classTime',
                render: (h, params) => {
                    return h('Select', {
                        props: {
                            value: this.dataListSchedule[params.index].classTime,
                            'label-in-value': true
                        },
                        on: {
                            'on-change': (event) => {
                                var index = params.index;
                                var obj = this.dataListSchedule[index];
                                obj.classTime = event.value;
                                obj.classTimeName = event.label;
                            }
                        }
                    },
                    [
                        h('Option', {
                            props: {
                                value: '1'
                            }
                        }, '周一'),
                        h('Option', {
                            props: {
                                value: '2'
                            }
                        }, '周二'),
                        h('Option', {
                            props: {
                                value: '3'
                            }
                        }, '周三'),
                        h('Option', {
                            props: {
                                value: '4'
                            }
                        }, '周四'),
                        h('Option', {
                            props: {
                                value: '5'
                            }
                        }, '周五'),
                        h('Option', {
                            props: {
                                value: '6'
                            }
                        }, '周六'),
                        h('Option', {
                            props: {
                                value: '7'
                            }
                        }, '周日')
                    ]);
                }
            }, {
                title: '教室',
                key: 'classRoom',
                render: (h, params) => {
                    var that = this;
                    return h('Input', {
                        props: {
                            icon: 'search',
                            readonly: true,
                            value: params.row.classRoom
                        },
                        on: {
                            'on-click': (event) => {
                                util.ajax.post('/base/classroom/list', util.toFormData(
                                )).then(res => {
                                    if (res.data.code == 200) {
                                        var data = res.data.data.list;
                                        this.dataListClassRoom = data;
                                    }
                                });
                                this.classRoomEntry = 1;// 因为选择教室的modal是公用的，所以要做一个入口标识
                                this.classRoomVisible = true;
                                this.currentDataListScheduleIndex = params.index;
                            }
                        }
                    });
                }
            }, {
                title: '开始时间',
                key: 'startTime',
                render: (h, params) => {
                    return h('TimePicker', {
                        props: {
                            format: 'HH:mm',
                            value: this.dataListSchedule[params.index].startTime
                        },
                        on: {
                            'on-change': (event) => {
                                this.dataListSchedule[params.index].startTime = event;
                            }
                        }
                    });
                }
            }, {
                title: '结束时间',
                key: 'endTime',
                render: (h, params) => {
                    return h('TimePicker', {
                        props: {
                            format: 'HH:mm',
                            value: this.dataListSchedule[params.index].endTime
                        },
                        on: {
                            'on-change': (event) => {
                                this.dataListSchedule[params.index].endTime = event;
                            }
                        }
                    });
                }
            }, {
                title: '操作',
                key: 'action',
                render: (h, params) => {
                    return h('div', [
                        h('Button', {
                            props: {
                                icon: 'plus',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                'click': (event) => {
                                    this.addRow(params.index, undefined);
                                }
                            }
                        }, '新增'),
                        h('Button', {
                            props: {
                                icon: 'minus',
                                size: 'small'
                            },
                            on: {
                                'click': (event) => {
                                    this.delRow(params);
                                }
                            }
                        }, '删除')
                    ]);
                }
            }],
            columns: [{
                width: 55,
                title: '#',
                type: 'selection'
            }, {
                title: '班级名称',
                key: 'name'
            }, {
                title: '专业',
                key: 'marjorName'
            }, {
                title: '开课时间',
                key: 'classStarttime',
                render: function (h, params) {
                    return h('div', util.getDate(params.row.classStarttime));/* 这里的this.row能够获取当前行的数据 */
                }
            }, {
                title: '预招(预留)人数',
                key: 'initiallyPeople',
                render: function (h, params) {
                    return h('div', params.row.initiallyPeople + '(' + params.row.reservedPeople + ')');
                }
            }, {
                title: '课程安排',
                key: 'classSchedules',
                width: 180,
                render: function (h, params) {
                    let list = params.row.classSchedules;
                    if (typeof (list) === 'string') {
                        list = JSON.parse(list);
                    }
                    let list_h = [];
                    for (let i in list) {
                        let startTime = list[i].classStartTime;
                        let endTime = list[i].classEndTime;
                        if (startTime) {
                            startTime = startTime.substring(0, 2) + ':' + startTime.substring(2, 4);
                        }
                        if (endTime) {
                            endTime = endTime.substring(0, 2) + ':' + endTime.substring(2, 4);
                        }
                        let fun = h('div', util.convertNumToWeekOfDay(list[i].classType) + ' ' + startTime + '-' + endTime + ' ' + list[i].classRoomName);
                        list_h.push(fun);
                    }
                    return h('span', list_h);
                }
            }, {
                title: '录取方式',
                key: 'classApply'
            }, {
                title: '班级状态',
                key: 'status',
                render: function (h, params) {
                    let text = '';
                    let status = params.row.status;
                    if (status == 1) {
                        text = '草稿';
                    } else if (status == 2) {
                        text = '核审通过';
                    } else if (status == 3) {
                        text = '核审未通过';
                    } else if (status == 4) {
                        text = '等待核审';
                    }
                    return h('div', {}, text);
                }
            }, {
                title: '操作',
                key: 'action',
                width: 200,
                align: 'center',
                render: (h, params) => {
                    return h('div', [
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.tagCloseableFlag = false;
                                    util.ajax.post('/base/class/detailsBySql', util.toFormData(
                                        {id: params.row.id}
                                    )).then(res => { // 获得区域数据
                                        if (res.data.code == 200) {
                                            this.$refs['formData'].resetFields();
                                            var data = res.data.data;
                                            this.showEdit(data);
                                        }
                                    });
                                }
                            }
                        }, '修改'),
                        h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            on: {
                                click: () => {
                                    let obj = [];
                                    obj.push(params.row.id);
                                    this.doDel(obj);
                                }
                            }
                        }, '删除')
                    ]);
                }
            }],
            dataList: [],
            addVisible: false, // 新增弹窗的显示和隐藏
            isRead: false, // 新增、编辑或查看时，数据是否可以修改
            areaList: [], // 区域列表
            formData: {
                name: '',
                code: '',
                classTime: 0,
                classYear: '',
                classSeason: '',
                classAreaId: '',
                departmentId: '',
                marjorName: '',
                marjorLevelId: '',
                mainTeacherName: '',
                classTimeRemarks: '',
                classRemark: '',
                classStarttime: '',
                classEndtime: '',
                initiallyPeople: '',
                reservedPeople: '',
                teachCost: 0,
                teachCostDiff: 0,
                otherCost: 0,
                classApplyType: '',
                classTimeJson: '',
                classScheduleJson: ''
            }, // 新增/编辑表单数据
            queryData: {}, // 查询表单数据
            entityData: {}, // 查看详情的数据
            pageSize: 15, // 分页数据
            pageIndex: 1, // 分页数据
            total: 0,
            deptModal: false,
            baseuser: JSON.parse(Cookies.get('baseUser')),
            query: {},
            departmentList: [],
            classSeasonList: [],
            majorLevelList: [],
            classAgeList: [],
            mainTeacherList: [],
            classApplyList: [],
            scheduleVisible: false,
            classRoomVisible: false,
            teachersVisible: false,
            currentDataListScheduleIndex: '', // 当前课表数组对象焦点
            dataListSchedule: [/* {
                                        "tempid":"",//临时id，记录新添加而没有保存的tag
                                        "id":'',
                                        "classTime":'',
                                        "classTimeName":'',
                                         "classRoomId":"",
                                        "classRoom":'',
                                        "startTime":'',
                                        "startTime":"",
                                        "endTime":"",
                                        "action":"",
                                  } */],
            dataListClassRoom: [],
            columnsClassRoom: [
                {
                    title: '#',
                    type: 'index'
                },
                {
                    title: '教室名称',
                    key: 'name'
                }, {
                    title: '所属部门',
                    key: 'name'
                }, {
                    title: '座位数量',
                    key: 'name'
                }
            ],
            startGrade: '',
            endGrade: '',
            orgList: [],
            marjorTreeVisible: false, // 专业树形弹窗
            marjorList: [], // 专业列表
            marjorFatherList: [], // 专业大类列表
            startAge: '',
            endAge: '',
            selection: [], // 选中行
            teacherList: [],
            columnsTeachers: [
            /*    {
                    title:"#",
                    type:"index"
                  }, */
                {
                    title: '教师姓名',
                    key: 'name'
                }, {
                    title: '性别',
                    key: 'gender',
                    render: (h, params) => {
                        let gender = params.row.gender;
                        let text = '';
                        if (gender == 'MAN') {
                            text = '男';
                        } else if (gender == 'WOMAN') {
                            text = '女';
                        }
                        return h('div', {}, text);
                    }
                }, {
                    title: '所属部门',
                    key: 'name'
                }, {
                    title: '出生日期',
                    key: 'birthday',
                    render: (h, params) => {
                        return h('div', util.getDate(params.row.birthday, 'date'));
                    }
                }, {
                    title: '职称',
                    key: 'technicalid',
                    render: (h, params) => {
                        return h('div', {}, params.row.technical.name);
                    }
                }],
            dataListTeachers: [],
            positionList: [],
            teacherQueryData: {
                pageSize: 5, // 分页数据
                pageIndex: 1, // 分页数据
                total: 0,
                name: ''
            },
            mainTeacherIdSelected: '',
            viceTeachersIdSelected: [],
            classTimeType: [],
            bathAddClassRoomScheduleVisible: false,
            bathAddClassRoomData: {
                classTime: []
            },
            classRoomEntry: '',
            weekData: [
                {id: 1, name: '周一'},
                {id: 2, name: '周二'},
                {id: 3, name: '周三'},
                {id: 4, name: '周四'},
                {id: 5, name: '周五'},
                {id: 6, name: '周六'},
                {id: 7, name: '周日'}
            ],
            booksVisible: false,
            bookList: [],
            classTimeVisible: false,
            classTimeList: [],
            classTimeData: {
                id: '',
                times: 0,
                price: 0
            },
            tagCloseableFlag: true, // 课表标签是否可以关闭
            priceDiff: 0,
            // formValidate: {
            //     name: { required: true, message: 'The name cannot be empty', trigger: 'blur' }
            // }
            formDataRules: {// 添加班级表单验证规则
                name: [
                    { required: true, message: '请输入班级名称', trigger: 'blur' }
                ],
                classTime: [
                    { required: true, message: '请确定课次', trigger: 'blur', type: 'number'}
                ],
                classYear: [
                    { required: true, message: '请选择学年', trigger: 'blur', type: 'string'}
                ],
                classAreaId: [
                    { type: 'number', required: true, message: '请选择区域', trigger: 'blur'}
                ],
                departmentId: [
                    { type: 'number', required: true, message: '请选择部门', trigger: 'blur'}
                ],
                marjorName: [
                    { required: true, message: '请选择专业', trigger: 'blur', type: 'string'}
                ],
                // classStarttime: [
                //     { required: true, message: '请选择开课时间', trigger: 'change', type: 'date'}
                // ],
                // classEndtime: [
                //     { required: true, message: '请选择结课时间', trigger: 'change', type: 'date'}
                // ],
                initiallyPeople: [
                    { required: true, message: '请输入预招人数', trigger: 'blur', type: 'string'}
                ],
                teachCost: [
                    { required: true, message: '请输入教学费', trigger: 'blur', type: 'string' }
                ],
                otherCost: [
                    { required: true, message: '请选择教材', trigger: 'blur' }
                ],
                classTimeJson: [
                    { required: true, message: '请确认课次', trigger: 'blur'}
                ],
                classScheduleJson: [
                    { required: true, message: '请确认课表', trigger: 'blur'}
                ],
                mainTeacherName: [
                    { required: true, message: '请选择负责教师', trigger: 'blur'}
                ],
                // classApplyType: [
                //     { required: true, message: '请选择录取方式', trigger: 'blur', type: 'number'}
                // ]
            },
            classTimeModelWeek: [],
            classTimeModelType: [],
            classTimeModelTypeEntity: 0,
            classTimeModelWeekEntity: 0,
            classTimeModelClassRoomName: '',
            classTimeModelClassRoomId: ''
        };
    },
    mounted () {
        this.classTimeModelType = classTimeModel.classTime;
        this.classTimeModelWeek = classTimeModel.classTimeWeek;
        this.init();
    },
    methods: {
        whenSelectOrg: function (event) {
            // 根据选择机构获得部门
            util.ajax.post('base/organize/getDepByOrgIdExceptOrg', util.toFormData({
                id: event
            })).then(res => {
                this.departmentList = res.data.data;
            });
        },
        init: function () { // 页面初始化
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'AREA_TYPE'}
            )).then(res => { // 获得区域数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.areaList = data;
                }
            });

            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'CLASS_SEASON'}
            )).then(res => { // 学期数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.classSeasonList = data;
                }
            });

            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'MAJOR_LEVEL'}
            )).then(res => { // 获得区域数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.majorLevelList = data;
                }
            });

            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'GRADE'}
            )).then(res => { // 年纪数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.classAgeList = data;
                }
            });

            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'CLASS_APPLY_TYPE'}
            )).then(res => { // 获得区域数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.classApplyList = data;
                }
            });

            util.ajax.post('/busine/teacher/list', util.toFormData(
                {id: 0}
            )).then(res => { // 获得老师
                if (res.data.code == 200) {
                    var data = res.data.data.list;
                    this.mainTeacherList = data;
                }
            });

            util.ajax.post('/busine/major/findByParent', util.toFormData(
                {parentid: 0}
            )).then(res => { // 获得专业大类
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.marjorFatherList = data;
                }
            });
            this.doQuery();
        },
        doQuery: function () {
            util.ajax.post('/base/class/list', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                name: this.query.name ? this.query.name : '',
                year: this.query.year ? this.query.year : '',
                classSeason: this.query.classSeason ? this.query.classSeason : '',
                areaId: this.query.classAreaId ? this.query.classAreaId : '',
                departmentId: this.query.departmentId ? this.query.departmentId : '',
                marjorId: this.query.marjorId ? this.query.marjorId : '',
                status: '1@3',
                organizeId: this.baseuser.orgId
            })).then(res => {
                if (res.data.data) {
                    this.dataList = res.data.data.list;
                    for (let i in this.dataList) {
                        this.dataList[i].classStarttime = utilDate.getDate(this.dataList[i].classStarttime, 'date');
                    }
                    this.total = res.data.data.total;
                }
            });
        },
        setDept () {
            if (this.$refs.dept.selectData[0]) {
                this.query.departmentId = this.$refs.dept.selectData[0].id;
                this.query.departmentName = this.$refs.dept.selectData[0].title;
            } else {
                this.query.departmentId = '';
                this.query.departmentName = '';
            }
            this.deptModal = false;
        },
        cancelSelect () {
            this.$refs.dept.cancelSelect();
        },
        refresh () {
            this.query = {};
            this.loadList();
        },
        showEdit: function (obj) {
            // this.formData = {
            //     name: '',
            //     classTime: 0,
            //     code: '',
            //     classYear: '',
            //     classSeason: '',
            //     classAreaId: '',
            //     departmentId: '',
            //     marjorName: '',
            //     marjorLevelId: '',
            //     mainTeacherName: '',
            //     classTimeRemarks: '',
            //     classRemark: '',
            //     classStarttime: '',
            //     classEndtime: '',
            //     initiallyPeople: '',
            //     reservedPeople: '',
            //     teachCost: 0,
            //     otherCost: 0,
            //     classApplyType: '',
            //     classTimeJson: '',
            //     classScheduleJson: ''
            // };
            this.dataListSchedule = [];
            this.classTimeList = [];
            this.bookList = [];

            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(// 获得课次类型
                {CODE: 'CLASS_TIME_TYPE'}
            )).then(res => {
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.classTimeType = data;
                } else {
                    this.$Message.error(res.data.message);
                }
            });

            util.ajax.post('/base/organize/findOrgByType', util.toFormData({
                type: 1
            })).then(res => { // 获得机构
                this.orgList = res.data.data;
            });

            util.ajax.post('base/organize/getDepByOrgIdExceptOrgByLoginUserOrg').then(res => {
                if (res.data.code == 200) {
                    this.departmentList = res.data.data;
                    // if (data.departmentId != null && data.departmentId != '') {
                    //     data.departmentId = parseInt(data.departmentId);
                    // }
                } else {
                    this.$Message.success(res.data.message);
                }
            });
            let classSchedules = obj.classSchedules;
            if (classSchedules) {
                for (let i in classSchedules) {
                    let item = {};
                    item.id = classSchedules[i].id;
                    item.classRoom = classSchedules[i].classRoomName;
                    let classType = classSchedules[i].classType;
                    item.classTime = classType;
                    item.classTimeName = util.convertNumToWeekOfDay(classType);
                    let startTime = classSchedules[i].classStartTime;
                    let endTime = classSchedules[i].classEndTime;
                    if (startTime != null && startTime != '') {
                        item.startTime = startTime.substring(0, 2) + ':' + startTime.substring(2, 4);
                    }
                    if (endTime != null && endTime != '') {
                        item.endTime = endTime.substring(0, 2) + ':' + endTime.substring(2, 4);
                    }
                    this.dataListSchedule.push(item);
                }
            }

            let classTimes = obj.classTimeJson;
            if (classTimes && typeof (classTimes) === 'string') {
                this.classTimeList = [];
                classTimes = JSON.parse(classTimes);
                for (let i in classTimes) {
                    let o = {
                        'id': classTimes[i].id,
                        'name': classTimes[i].name,
                        'times': classTimes[i].times,
                        'price': classTimes[i].price
                    };
                    this.classTimeList.push(o);
                }
            }

            let books = obj.booksJson;
            if (books && typeof (books) === 'string') {
                this.bookList = [];
                books = JSON.parse(books);
                for (let i in books) {
                    let o = {
                        'id': books[i].id,
                        'name': books[i].name
                    };
                    this.bookList.push(o);
                }
            }

            obj.classEndtime = utilDate.getDate(obj.classEndtime, 'date');
            obj.classStarttime = utilDate.getDate(obj.classStarttime, 'date');
            this.formData = obj;
            this.tagCloseableFlag = false;
            this.addVisible = true;
        },
        showAdd: function (obj) {
            let loginUser = Cookies.get('baseUser');
            if (typeof (loginUser) === 'string') {
                loginUser = JSON.parse(loginUser);
            }
            this.formData = {
                name: '',
                classTime: 0,
                code: '',
                classYear: '',
                classSeason: '',
                classAreaId: loginUser.areaId,
                departmentId: '',
                marjorName: '',
                marjorLevelId: '',
                mainTeacherName: '',
                classTimeRemarks: '',
                classRemark: '',
                classStarttime: '',
                classEndtime: '',
                initiallyPeople: '',
                reservedPeople: '',
                teachCost: 0,
                teachCostDiff: 0,
                otherCost: 0,
                classApplyType: '',
                classTimeJson: '',
                classScheduleJson: ''
            };
            this.dataListSchedule = [];
            this.classTimeList = [];
            this.bookList = [];

            util.ajax.post('base/organize/getDepByOrgIdExceptOrgByLoginUserOrg').then(res => {
                if (res.data.code == 200) {
                    this.departmentList = res.data.data;
                } else {
                    this.$Message.success(res.data.message);
                }
            });
            this.tagCloseableFlag = true;
            this.addVisible = true;
        },
        doDel: function (ids) {
            if (ids) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '确认删除？',
                    onOk: () => {
                        util.ajax.post('/base/class/delete', util.toFormData({ids: ids.join('@')})).then(res => {
                            if (res.data.code == 200) {
                                if (res.data.message == 'SUCCESS') {
                                    this.$Message.success('删除成功！');
                                    this.pageIndex = 1;
                                    this.init();
                                } else {
                                    this.$Message.warning(res.data.message || '未知错误！');
                                }
                            }
                        });
                    },
                    onCancel: () => {

                    }
                });
            } else {
                this.$Modal.error({content: '请选择删除项!'});
            }
        },
        doSave: function (name) {
            let that = this;
            let formData = this.formData;
            this.formData.classStarttime = (this.formData.classStarttime != '' ? new Date(formData.classStarttime) : '');
            this.formData.classEndtime = (this.formData.classEndtime != '' ? new Date(formData.classEndtime) : '');
            this.formData.classTimeJson = this.classTimeList.length <= 0 ? '' : JSON.stringify(this.classTimeList);
            this.formData.booksJson = this.bookList.length <= 0 ? '' : JSON.stringify(this.bookList);
            this.formData.teachCost = this.formData.teachCost + '';
            this.formData.initiallyPeople = this.formData.initiallyPeople + '';
            this.formData.classScheduleJson = this.dataListSchedule.length <= 0 ? '' : JSON.stringify(this.dataListSchedule);
            this.formData.mainTeacherId = this.mainTeacherIdSelected;
            delete this.formData.classSchedules;
            delete this.formData.createTime;
            delete this.formData.updateTime;
            this.$refs[name].validate((valid) => { // 表单验证
                if (valid) {
                    util.ajax.post('/base/class/save', util.toFormData(formData)).then(res => {
                        if (res.data.code == 200) {
                            if (res.data.message == 'SUCCESS') {
                                this.$Message.success('保存成功！');
                                this.addVisible = false;
                                this.pageIndex = 1;
                                this.init();
                            } else {
                                this.$Message.warning(res.data.message || '未知错误！');
                                this.addVisible = false;
                            }
                            this.formData = {};
                        }
                    });
                } else {
                    this.$Message.warning('请检查输入项！');
                }
            });
        },
        showClassSchedule: function () {
            this.scheduleVisible = true;
        },
        addRow: function (index, obj) {
            if (obj == undefined) {
                obj = {
                    'tempid': index,
                    'id': '',
                    'classRoomId': '',
                    'classTime': '',
                    'classTimeName': '',
                    'classRoom': '',
                    'startTime': '',
                    'endTime': '',
                    'action': ''
                };
            }
            this.dataListSchedule.push(obj);
        },
        delRow: function (params) {
            var index = params.index;
            this.dataListSchedule.splice(index, 1);
        },
        // whenClassRoomSelect: function (currentRow, oldCurrentRow) {
        //     let flag = this.classRoomEntry;
        //     if (flag == 1) {
        //         var index = this.currentDataListScheduleIndex;
        //         if (index || index == 0) {
        //             var obj = this.dataListSchedule[index];// 当前课表焦点
        //             obj.classRoomId = currentRow.id;
        //             obj.classRoom = currentRow.name;
        //         }
        //     } else if (flag = 2) {
        //         this.bathAddClassRoomData.classRoomName = currentRow.name;
        //         this.bathAddClassRoomData.classRoomId = currentRow.id;
        //     }
        // },
        whenCloseTag: function (event, name) {
            var id = name.id;
            var tempid = name.tempid;
            var delIndex = '';
            var list = this.dataListSchedule;
            for (let i in list) {
                if (list[i].id != null && list[i].id != '' && list[i].id != undefined) {
                    if (id == list[i].id) {
                        delIndex = i;
                        break;
                    }
                } else if (list[i].tempid != null && list[i].tempid != '' && list[i].tempid != undefined) {
                    if (tempid == list[i].tempid) {
                        delIndex = i;
                        break;
                    }
                }
            }
            this.dataListSchedule.splice(delIndex, 1);
        },
        whenTapMarjor: function () {
            util.ajax.post('/busine/major/findAll', util.toFormData()).then(res => {
                if (res.data.code == 200) {
                    let data = res.data.data;
                    let tree = [];
                    for (let i in data) {
                        if (data[i].parentid == 0) { // 第一次循环父节点
                            tree.push({
                                id: data[i].id,
                                title: data[i].name,
                                expand: false,
                                children: []
                            });
                        }
                    }
                    if (tree.length > 0) {
                        this.createTree(tree, data);
                    }
                    this.marjorList = tree;
                    this.marjorTreeVisible = true;
                }
            });
        },
        createTree: function (tree, data) {
            let childTree = [];
            let _this = this;
            tree.forEach(treeItem => {
                childTree = [];
                data.forEach(dataItem => {
                    if (treeItem.id === dataItem.parentid) {
                        childTree.push({
                            id: dataItem.id,
                            title: dataItem.name,
                            expand: true,
                            children: []
                        });
                    }
                });
                if (childTree.length > 0) {
                    treeItem.children = childTree;
                    _this.createTree(childTree, data);
                }
            });
        },
        whenSelectMarjor: function (res) {
            var id = res[0].id;
            var name = res[0].title;
            this.formData.marjorName = name + '';
            this.formData.marjorId = id;
        },
        doSubmitApproveBath: function () { // 批量送审
            let list = this.selection;
            if (list.length == 0) {
                this.$Message.error('请选择送审项目');
                return;
            }
            var ids = [];
            for (let i in list) {
                ids.push(list[i].id);
            }
            util.ajax.post('/base/class/doApprove', util.toFormData({
                ids: ids.join('@'),
                flag: 4
            })).then(res => {
                if (res.data.code == 200) {
                    if (res.data.message) {
                        this.$Message.success('操作成功!');
                    } else {
                        this.$Message.error('操作失败!');
                    }
                } else {
                    this.$Message.error('操作失败!');
                }
                this.init();
            });
        },
        doDelBath: function (selection) { // 批量删除
            let list = this.selection;
            if (list.length == 0) {
                this.$Message.error('请选择删除项目');
                return;
            }
            var ids = [];
            for (let i in list) {
                ids.push(list[i].id);
            }
            this.doDel(ids);
        },
        whenSelectRow: function (selection) {
            // var id = currentRow.id;
            // this.entityData.id = id;
            this.selection = selection;
        },
        selectMainTeacher: function () {
            var list = this.columnsTeachers;
            if (list.length == 5) {
                list.unshift({
                    'title': '#',
                    'type': 'index'
                });
            } else if (list.length == 6) {
                list.splice(0, 1);
                list.unshift({
                    'title': '#',
                    'type': 'index'
                });
            }

            this.columnsTeachers = list;
            this.teacherInit();
            this.teachersVisible = true;
        },
        teacherInit: function () {
            util.ajax.post('/busine/teacher/list', util.toFormData(
                {
                    page: this.teacherQueryData.pageIndex,
                    size: this.teacherQueryData.pageSize,
                    name: this.teacherQueryData.name
                }
            )).then(res => { // 获得=职称
                this.dataListTeachers = res.data.data.list;
                this.teacherQueryData.total = res.data.data.total;
            });
        },
        doTeacherQuery: function () {
            this.teacherInit();
        },
        whenTeacherSelected: function (selection) { // 多选
            let ids = '';
            let names = '';
            for (let i in selection) {
                let id = selection[i].id;
                let name = selection[i].name;
                if (i == 0) {
                    ids = id;
                    names = name;
                } else {
                    ids += '@' + id;
                    names += ',' + name;
                }
            }
            this.viceTeachersIdSelected = ids;
            this.formData.viceTeacherName = names;
        },
        whenTeacherChange: function (currentRow, oldCurrentRow) { // 单选
            this.formData.mainTeacherName = currentRow.name;
            this.mainTeacherIdSelected = currentRow.id;
        },
        selectViceTeacher: function () {
            var list = this.columnsTeachers;
            if (list.length == 5) {
                list.unshift({
                    'title': '#',
                    'type': 'selection'
                });
            } else if (list.length == 6) {
                list.splice(0, 1);
                list.unshift({
                    'title': '#',
                    'type': 'selection'
                });
            }

            this.columnsTeachers = list;
            this.teacherInit();
            this.teachersVisible = true;
        },
        showClassRoomSelecter: function () {
            util.ajax.post('/base/classroom/list', util.toFormData(
            )).then(res => {
                if (res.data.code == 200) {
                    var data = res.data.data.list;
                    this.dataListClassRoom = data;
                }
            });
            this.classRoomVisible = true;
            this.classRoomEntry = 2;
        },
        bathAddClassRoomScheduleClose: function () {
            this.bathAddClassRoomScheduleVisible = false;
        },
        bathAddClassRoomSchedule: function () {
            this.bathAddClassRoomScheduleVisible = true;
            this.bathAddClassRoomData = {
                classTime: []
            };
        },
        bathAddClassRoomConfirm: function () {
            let data = this.bathAddClassRoomData;
            let classTimes = data.classTime;
            if (data.classTime == null || data.classTime == '' || data.classTime == undefined || data.classTime.length == 0) {
                this.$Modal.warning({content: '请选择上课周期'});
                return;
            }
            let first_index = this.dataListSchedule.length;
            for (let i in classTimes) {
                let d = classTimes[i];
                let index = first_index;
                let classTimeName = '';
                switch (d + '') {
                    case '1':
                        classTimeName = '周一';
                        break;
                    case '2':
                        classTimeName = '周二';
                        break;
                    case '3':
                        classTimeName = '周三';
                        break;
                    case '4':
                        classTimeName = '周四';
                        break;
                    case '5':
                        classTimeName = '周五';
                        break;
                    case '6':
                        classTimeName = '周六';
                        break;
                    case '7':
                        classTimeName = '周日';
                        break;
                    default:
                        break;
                }

                let obj = {
                    'tempid': index,
                    'id': '',
                    'classRoomId': data.classRoomId,
                    'classTime': d + '',
                    'classTimeName': classTimeName,
                    // 'classTimeName': d.name,
                    'classRoom': data.classRoomName,
                    'startTime': data.classStartTime,
                    'endTime': data.classEndTime,
                    'action': ''
                };
                this.dataListSchedule.push(obj);
                first_index++;
            }
            this.bathAddClassRoomScheduleVisible = false;
            this.bathAddClassRoomData = {
                classTime: []
            };
        },
        bathAddClassOnChange: function (event) {
            // console.log(event);
            // this.bathAddClassRoomData.classTime = [];
            // for (let i = 0; i < event.length; i++) {
            //     let obj = {
            //         id: (i + 1),
            //         name: event[i]
            //     };
            //     this.bathAddClassRoomData.classTime.push(obj);
            // }
            console.log(this.bathAddClassRoomData.classTime);
        },
        whenSelectBook: function () {
            this.bookList = this.$refs.books.books;
            // 计算教材费
            let bookList = this.bookList;
            let total = 0;
            for (let i in bookList) {
                let price = bookList[i].price;
                total += price;
            }
            this.formData.otherCost = total;
        },
        whenDelBooks: function (event, name) {
            var id = name.id;
            var delIndex = '';
            var list = this.bookList;
            for (let i in list) {
                if (list[i].id != null && list[i].id != '' && list[i].id != undefined) {
                    if (id == list[i].id) {
                        delIndex = i;
                        break;
                    }
                }
            }
            let price = this.bookList[delIndex].price;
            this.formData.otherCost = this.formData.otherCost - price;
            this.bookList.splice(delIndex, 1);
        },
        addClassTime: function () {
            let times = this.classTimeData.times;
            let name = this.classTimeData.name;
            let price = this.classTimeData.price;
            let obj = {
                times: times,
                name: name,
                price: price
            };
            this.classTimeList.push(obj);
            this.classTimeVisible = false;
            this.classTimeData = {
                id: '',
                times: 0
            };
        },
        whenCloseClassTime: function (event, name) {
            var id = name.id;
            var delIndex = '';
            var list = this.classTimeList;
            for (let i in list) {
                if (list[i].id != null && list[i].id != '' && list[i].id != undefined) {
                    if (id == list[i].id) {
                        delIndex = i;
                        break;
                    }
                }
            }
            this.classTimeList.splice(delIndex, 1);
        },
        whenBathClassStartTimeChange: function (event) {
            this.bathAddClassRoomData.classStartTime = event;
        },
        whenBathClassEndTimeChange: function (event) {
            this.bathAddClassRoomData.classEndTime = event;
        },
        judgeMarjorType: function () { // 判断是否选择了专业大类
            let marjorId = this.formData.marjorId;
            if (marjorId != '' && (marjorId + '').length == 3) {
                this.$Message.warning('不能选择专业大类，请重新选择');
                this.formData.marjorName = '';
                this.formData.marjorId = '';
            }
        },
        whenSetMarjor: function () {
            this.judgeMarjorType();
        },
        whenMarjorTreeVisibleChange: function (flag) {
            if (!flag) {
                this.judgeMarjorType();
            }
        },

        whenSetClassRoom: function () {
            let flag = this.classRoomEntry;
            if (flag == 1) {
                var index = this.currentDataListScheduleIndex;
                if (index || index == 0) {
                    var obj = this.dataListSchedule[index];// 当前课表焦点
                    obj.classRoomId = this.$refs.classroomComp.classRoomSelected.id;
                    obj.classRoom = this.$refs.classroomComp.classRoomSelected.name;
                }
            } else if (flag == 2) {
                this.bathAddClassRoomData.classRoomName = this.$refs.classroomComp.classRoomSelected.name;
                this.bathAddClassRoomData.classRoomId = this.$refs.classroomComp.classRoomSelected.id;
            } else if (flag == 3) {
                this.classTimeModelClassRoomName = this.$refs.classroomComp.classRoomSelected.name;
                this.classTimeModelClassRoomId = this.$refs.classroomComp.classRoomSelected.id;
            }
        },
        addModelToScheduleList: function () {
            let first_index = this.dataListSchedule.length;
            var obj = {
                'tempid': first_index,
                'id': '',
                'classRoomId': this.classTimeModelClassRoomId,
                'classRoom': this.classTimeModelClassRoomName,
                'action': ''
            };

            if (this.classTimeModelWeekEntity && this.classTimeModelWeekEntity != 0) {
                for (let i in this.classTimeModelWeek) {
                    let k = this.classTimeModelWeek[i].k;
                    if (k == this.classTimeModelWeekEntity) {
                        obj.classTime = k;
                        obj.classTimeName = this.classTimeModelWeek[i].v;
                        break;
                    }
                }
            }

            if (this.classTimeModelTypeEntity && this.classTimeModelTypeEntity != 0) {
                for (let i in this.classTimeModelType) {
                    let k = this.classTimeModelType[i].k;
                    if (k == this.classTimeModelTypeEntity) {
                        let time = this.classTimeModelType[i].v;
                        if (time) {
                            time = time.split('-');
                            obj.startTime = time[0];
                            obj.endTime = time[1];
                        }
                        break;
                    }
                }
            }

            this.dataListSchedule.push(obj);
        },
        showClassRoomSelecterForClassTimeModel: function () {
            util.ajax.post('/base/classroom/list', util.toFormData(
            )).then(res => {
                if (res.data.code == 200) {
                    var data = res.data.data.list;
                    this.dataListClassRoom = data;
                }
            });
            this.classRoomVisible = true;
            this.classRoomEntry = 3;
        },
        refreshClassTimeMolde: function () {
            this.classTimeModelTypeEntity = 0;
            this.classTimeModelWeekEntity = 0;
            this.classTimeModelClassRoomName = '';
            this.classTimeModelClassRoomId = '';
        }
    }
};
